/**
 * 数据转换工具
 * 支持多种地理数据格式之间的转换
 */

const fs = require('fs');
const path = require('path');
const shapefile = require('shapefile');
const shpwrite = require('shp-write');
const iconv = require('iconv-lite');
const csv = require('csv-parser');
const FileHelper = require('../utils/file-helper');
const Logger = require('../utils/logger');

class DataConvertTool {
    constructor() {
        this.isProcessing = false;
        this.currentConvertType = 'shp2geojson';
        
        // 初始化工具类
        this.logger = new Logger('convertLogContainer');
        
        // DOM元素引用
        this.elements = null;
        
        // 立即初始化
        setTimeout(() => this.init(), 100);
    }

    /**
     * 获取DOM元素引用
     * @returns {Object} DOM元素对象
     */
    getElements() {
        return {
            convertType: document.getElementById('convertType'),
            convertInputFile: document.getElementById('convertInputFile'),
            convertOutputFile: document.getElementById('convertOutputFile'),
            selectConvertInputBtn: document.getElementById('selectConvertInputBtn'),
            selectConvertOutputBtn: document.getElementById('selectConvertOutputBtn'),
            preserveProperties: document.getElementById('preserveProperties'),
            simplifyGeometry: document.getElementById('simplifyGeometry'),
            encodingSelect: document.getElementById('encodingSelect'),
            csvCoordinateSection: document.getElementById('csvCoordinateSection'),
            csvXColumnSelect: document.getElementById('csvXColumnSelect'),
            csvYColumnSelect: document.getElementById('csvYColumnSelect'),
            previewCsvBtn: document.getElementById('previewCsvBtn'),
            encodingSection: document.getElementById('encodingSection'),
            convertProgressSection: document.getElementById('convertProgressSection'),
            convertProgressFill: document.getElementById('convertProgressFill'),
            convertProgressText: document.getElementById('convertProgressText'),
            convertProgressPercent: document.getElementById('convertProgressPercent'),
            startConvertBtn: document.getElementById('startConvertBtn'),
            previewBtn: document.getElementById('previewBtn'),
            clearConvertBtn: document.getElementById('clearConvertBtn')
        };
    }

    /**
     * 初始化工具
     */
    init() {
        this.elements = this.getElements();
        this.bindEvents();
        this.updateConvertOptions();
        this.logger.info('数据转换工具已初始化');
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        const { elements } = this;

        // 转换类型变化事件
        elements.convertType?.addEventListener('change', () => this.onConvertTypeChange());

        // 文件选择事件
        elements.selectConvertInputBtn?.addEventListener('click', () => this.selectInputFile());
        elements.selectConvertOutputBtn?.addEventListener('click', () => this.selectOutputFile());

        // 控制按钮事件
        elements.startConvertBtn?.addEventListener('click', () => this.startConversion());
        elements.previewBtn?.addEventListener('click', () => this.previewData());
        elements.clearConvertBtn?.addEventListener('click', () => this.clearSettings());
        elements.previewCsvBtn?.addEventListener('click', () => this.previewCsvData());

        // 表单变化事件
        elements.convertInputFile?.addEventListener('change', () => this.onInputFileChange());
        elements.convertOutputFile?.addEventListener('change', () => this.updateButtons());
        
        // CSV坐标列选择事件
        elements.csvXColumnSelect?.addEventListener('change', () => this.updateButtons());
        elements.csvYColumnSelect?.addEventListener('change', () => this.updateButtons());
    }

    /**
     * 转换类型变化处理
     */
    onConvertTypeChange() {
        this.currentConvertType = this.elements.convertType.value;
        this.updateConvertOptions();
        this.clearFiles();
        this.logger.info(`已切换到转换类型: ${this.getConvertTypeName()}`);
    }

    /**
     * 获取转换类型名称
     * @returns {string} 转换类型名称
     */
    getConvertTypeName() {
        const typeNames = {
            'shp2geojson': 'Shapefile转GeoJSON',
            'geojson2shp': 'GeoJSON转Shapefile',
            'csv2geojson': 'CSV转GeoJSON'
        };
        return typeNames[this.currentConvertType] || '未知类型';
    }

    /**
     * 更新转换选项显示
     */
    updateConvertOptions() {
        // 根据转换类型显示/隐藏相关选项
        const encodingSection = this.elements.encodingSection;
        const geometrySection = document.getElementById('geometrySection');
        const csvCoordinateSection = this.elements.csvCoordinateSection;
        
        // 隐藏所有特定选项
        encodingSection?.classList.add('hidden');
        geometrySection?.classList.add('hidden');
        csvCoordinateSection?.classList.add('hidden');
        
        // 根据转换类型显示相应选项
        if (this.currentConvertType === 'shp2geojson') {
            encodingSection?.classList.remove('hidden');
            geometrySection?.classList.remove('hidden');
        } else if (this.currentConvertType === 'csv2geojson') {
            encodingSection?.classList.remove('hidden');
            csvCoordinateSection?.classList.remove('hidden');
        }
        
        this.updateButtons();
    }

    /**
     * 选择输入文件
     */
    async selectInputFile() {
        try {
            const { ipcRenderer } = require('electron');
            const filters = this.getInputFileFilters();
            const result = await ipcRenderer.invoke('select-file', { filters });
            
            if (!result.canceled && result.filePaths.length > 0) {
                this.elements.convertInputFile.value = result.filePaths[0];
                this.onInputFileChange();
                this.logger.info(`已选择输入文件: ${path.basename(result.filePaths[0])}`);
            }
        } catch (error) {
            this.logger.error(`选择输入文件失败: ${error.message}`);
        }
    }

    /**
     * 选择输出文件
     */
    async selectOutputFile() {
        try {
            const { ipcRenderer } = require('electron');
            const filters = this.getOutputFileFilters();
            const result = await ipcRenderer.invoke('select-save-path', { filters });
            
            if (!result.canceled && result.filePath) {
                this.elements.convertOutputFile.value = result.filePath;
                this.updateButtons();
                this.logger.info(`已设置输出路径: ${path.basename(result.filePath)}`);
            }
        } catch (error) {
            this.logger.error(`选择输出路径失败: ${error.message}`);
        }
    }

    /**
     * 获取输入文件过滤器
     * @returns {Array} 文件过滤器数组
     */
    getInputFileFilters() {
        const filterMap = {
            'shp2geojson': [
                { name: 'Shapefile', extensions: ['shp'] },
                { name: '所有文件', extensions: ['*'] }
            ],
            'geojson2shp': [
                { name: 'GeoJSON', extensions: ['geojson', 'json'] },
                { name: '所有文件', extensions: ['*'] }
            ],
            'csv2geojson': [
                { name: 'CSV文件', extensions: ['csv'] },
                { name: '文本文件', extensions: ['txt'] },
                { name: '所有文件', extensions: ['*'] }
            ]
        };
        
        return filterMap[this.currentConvertType] || [{ name: '所有文件', extensions: ['*'] }];
    }

    /**
     * 获取输出文件过滤器
     * @returns {Array} 文件过滤器数组
     */
    getOutputFileFilters() {
        const filterMap = {
            'shp2geojson': [
                { name: 'GeoJSON', extensions: ['geojson'] },
                { name: 'JSON', extensions: ['json'] }
            ],
            'geojson2shp': [
                { name: 'Shapefile', extensions: ['shp'] }
            ],
            'csv2geojson': [
                { name: 'GeoJSON', extensions: ['geojson'] },
                { name: 'JSON', extensions: ['json'] }
            ]
        };
        
        return filterMap[this.currentConvertType] || [{ name: '所有文件', extensions: ['*'] }];
    }

    /**
     * 开始转换
     */
    async startConversion() {
        if (this.isProcessing) {
            this.logger.warning('转换正在进行中，请稍候...');
            return;
        }

        const inputPath = this.elements.convertInputFile.value;
        const outputPath = this.elements.convertOutputFile.value;

        if (!inputPath || !outputPath) {
            this.logger.error('请选择输入文件和输出路径');
            return;
        }

        this.isProcessing = true;
        this.updateButtons();
        this.showProgress();

        try {
            this.logger.info(`开始转换: ${this.getConvertTypeName()}`);
            
            const options = {
                preserveProperties: this.elements.preserveProperties?.checked || false,
                simplifyGeometry: this.elements.simplifyGeometry?.checked || false,
                encoding: this.elements.encodingSelect?.value || 'utf8'
            };

            switch (this.currentConvertType) {
                case 'shp2geojson':
                    await this.convertShapefileToGeoJSON(inputPath, outputPath, options);
                    break;
                case 'geojson2shp':
                    await this.convertGeoJSONToShp(inputPath, outputPath, options);
                    break;
                case 'csv2geojson':
                    await this.convertCSVToGeoJSON(inputPath, outputPath, options);
                    break;
                default:
                    throw new Error(`不支持的转换类型: ${this.currentConvertType}`);
            }

            this.logger.success('转换完成！');
            
        } catch (error) {
            this.logger.error(`转换失败: ${error.message}`);
        } finally {
            this.isProcessing = false;
            this.updateButtons();
            this.hideProgress();
        }
    }

    /**
     * Shapefile转GeoJSON
     */
    async convertShapefileToGeoJSON(inputPath, outputPath, options) {
        this.updateProgress(10, '正在读取Shapefile...');
        
        try {
            const encoding = options.encoding === 'utf8' ? 'utf8' : options.encoding;
            let featureCount = 0;
            const features = [];
            
            await shapefile.read(inputPath, undefined, { encoding })
                .then(collection => {
                    if (collection && collection.features) {
                        collection.features.forEach(feature => {
                            if (feature && feature.geometry) {
                                if (options.preserveProperties) {
                                    features.push(feature);
                                } else {
                                    features.push({
                                        type: 'Feature',
                                        geometry: feature.geometry,
                                        properties: { id: featureCount + 1 }
                                    });
                                }
                                featureCount++;
                            }
                        });
                    }
                });
            
            this.updateProgress(70, '正在生成GeoJSON...');
            
            const geojson = {
                type: 'FeatureCollection',
                features: features
            };
            
            this.updateProgress(90, '正在写入文件...');
            
            fs.writeFileSync(outputPath, JSON.stringify(geojson, null, 2));
            
            this.updateProgress(100, '转换完成');
            
            this.logger.success(`成功转换 ${featureCount} 个要素到 ${outputPath}`);
            
        } catch (error) {
            throw new Error(`Shapefile转GeoJSON失败: ${error.message}`);
        }
    }

    /**
     * GeoJSON转SHP
     */
    async convertGeoJSONToShp(inputPath, outputPath, options) {
        this.updateProgress(10, '正在读取GeoJSON文件...');
        
        try {
            // 读取GeoJSON文件
            const geojsonContent = fs.readFileSync(inputPath, 'utf8');
            const geojson = JSON.parse(geojsonContent);
            
            this.updateProgress(30, '正在验证GeoJSON格式...');
            
            // 验证GeoJSON格式
            if (!geojson) {
                throw new Error('无效的GeoJSON文件');
            }
            
            // 处理单个Feature或FeatureCollection
            let features = [];
            if (geojson.type === 'FeatureCollection' && Array.isArray(geojson.features)) {
                features = geojson.features;
            } else if (geojson.type === 'Feature') {
                features = [geojson];
            } else {
                throw new Error('不支持的GeoJSON格式，必须是Feature或FeatureCollection类型');
            }
            
            this.updateProgress(50, '正在处理要素...');
            
            // 过滤有效要素
            const validFeatures = features.filter(feature => {
                return feature && feature.geometry && feature.type === 'Feature';
            });
            
            if (validFeatures.length === 0) {
                throw new Error('GeoJSON文件中没有有效的要素');
            }
            
            this.updateProgress(70, '正在生成Shapefile...');
            
            // 准备输出目录和文件名
            const outputDir = path.dirname(outputPath);
            const baseName = path.basename(outputPath, '.shp');
            
            // 确保输出目录存在
            if (!fs.existsSync(outputDir)) {
                fs.mkdirSync(outputDir, { recursive: true });
            }
            
            this.updateProgress(85, '正在写入文件...');
            
            // 准备要素数据
            const processedFeatures = validFeatures.map((feature, index) => {
                const result = {
                    type: 'Feature',
                    geometry: feature.geometry
                };
                
                // 处理属性
                if (options.preserveProperties && feature.properties && typeof feature.properties === 'object') {
                    // 清理属性，确保所有值都是基本类型，并限制字段名长度
                    const cleanProperties = {};
                    for (const [key, value] of Object.entries(feature.properties)) {
                        if (value !== null && value !== undefined) {
                            const cleanKey = key.substring(0, 10); // DBF字段名限制为10个字符
                            if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
                                // 限制字符串长度，避免DBF字段过长
                                if (typeof value === 'string' && value.length > 254) {
                                    cleanProperties[cleanKey] = value.substring(0, 254);
                                } else {
                                    cleanProperties[cleanKey] = value;
                                }
                            } else {
                                cleanProperties[cleanKey] = String(value).substring(0, 254);
                            }
                        }
                    }
                    result.properties = cleanProperties;
                } else {
                    result.properties = { 
                        id: index + 1,
                        name: `feat_${index + 1}`
                    };
                }
                
                return result;
            });
            
            // 创建FeatureCollection
            const collection = {
                type: 'FeatureCollection',
                features: processedFeatures
            };
            
            try {
                // 使用shp-write的zip方法生成Shapefile
                const zipBuffer = shpwrite.zip(collection);
                
                // 使用JSZip解压并保存文件
                const JSZip = require('jszip');
                const zip = new JSZip();
                
                const zipContent = await zip.loadAsync(zipBuffer);
                const promises = [];
                
                zipContent.forEach((relativePath, file) => {
                    if (!file.dir) {
                        const ext = path.extname(relativePath);
                        const newFileName = `${baseName}${ext}`;
                        const outputFilePath = path.join(outputDir, newFileName);
                        
                        promises.push(
                            file.async('nodebuffer').then(content => {
                                fs.writeFileSync(outputFilePath, content);
                                return outputFilePath;
                            })
                        );
                    }
                });
                
                const files = await Promise.all(promises);
                
                this.updateProgress(100, '转换完成');
                this.logger.success(`成功转换 ${validFeatures.length} 个要素`);
                this.logger.info(`生成Shapefile文件: ${files.map(f => path.basename(f)).join(', ')}`);
                this.logger.info(`输出目录: ${outputDir}`);
                
            } catch (shpError) {
                // 如果Shapefile生成失败，回退到GeoJSON格式
                this.logger.warning('Shapefile生成失败，生成GeoJSON格式作为替代');
                const geojsonPath = path.join(outputDir, `${baseName}.geojson`);
                fs.writeFileSync(geojsonPath, JSON.stringify(collection, null, 2));
                
                this.updateProgress(100, '转换完成');
                this.logger.success(`成功转换 ${validFeatures.length} 个要素`);
                this.logger.info(`生成GeoJSON文件: ${path.basename(geojsonPath)}`);
                this.logger.info(`输出目录: ${outputDir}`);
                this.logger.warning(`Shapefile生成失败原因: ${shpError.message}`);
            }
            
        } catch (error) {
            throw new Error(`GeoJSON转SHP失败: ${error.message}`);
        }
    }

    /**
     * CSV转GeoJSON
     * @param {string} inputPath - 输入文件路径
     * @param {string} outputPath - 输出文件路径
     * @param {Object} options - 转换选项
     */
    async convertCSVToGeoJSON(inputPath, outputPath, options) {
        this.updateProgress(10, '正在读取CSV文件...');
        
        try {
            const xColumnIndex = parseInt(this.elements.csvXColumnSelect.value);
            const yColumnIndex = parseInt(this.elements.csvYColumnSelect.value);
            
            if (isNaN(xColumnIndex) || isNaN(yColumnIndex)) {
                throw new Error('请选择X和Y坐标列');
            }
            
            if (xColumnIndex === yColumnIndex) {
                throw new Error('X和Y坐标列不能相同');
            }
            
            this.updateProgress(20, '正在解析CSV数据...');
            
            const encoding = options.encoding || 'utf8';
            const content = fs.readFileSync(inputPath, encoding);
            const lines = content.split('\n').filter(line => line.trim());
            
            if (lines.length < 2) {
                throw new Error('CSV文件至少需要包含标题行和一行数据');
            }
            
            // 解析标题行
            const headers = this.parseCSVLine(lines[0]);
            const xColumnName = headers[xColumnIndex];
            const yColumnName = headers[yColumnIndex];
            
            this.logger.info(`使用坐标列: X=${xColumnName}, Y=${yColumnName}`);
            
            this.updateProgress(40, '正在转换数据...');
            
            const features = [];
            let validCount = 0;
            let invalidCount = 0;
            
            // 处理数据行
            for (let i = 1; i < lines.length; i++) {
                const columns = this.parseCSVLine(lines[i]);
                
                if (columns.length < Math.max(xColumnIndex, yColumnIndex) + 1) {
                    invalidCount++;
                    continue;
                }
                
                const xValue = columns[xColumnIndex];
                const yValue = columns[yColumnIndex];
                
                // 尝试解析坐标
                const x = parseFloat(xValue);
                const y = parseFloat(yValue);
                
                if (isNaN(x) || isNaN(y)) {
                    invalidCount++;
                    continue;
                }
                
                // 验证坐标范围
                if (x < -180 || x > 180 || y < -90 || y > 90) {
                    this.logger.warning(`第${i}行坐标超出有效范围: (${x}, ${y})`);
                    invalidCount++;
                    continue;
                }
                
                // 创建属性对象
                const properties = {};
                headers.forEach((header, index) => {
                    if (index !== xColumnIndex && index !== yColumnIndex) {
                        properties[header] = columns[index] || '';
                    }
                });
                
                // 添加坐标信息到属性
                properties[xColumnName] = x;
                properties[yColumnName] = y;
                properties['row_id'] = validCount + 1;
                
                // 创建GeoJSON要素
                const feature = {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [x, y]
                    },
                    properties: properties
                };
                
                features.push(feature);
                validCount++;
                
                // 更新进度
                if (i % 100 === 0) {
                    const progress = 40 + (i / lines.length) * 40;
                    this.updateProgress(progress, `已处理 ${i}/${lines.length - 1} 行数据...`);
                }
            }
            
            this.updateProgress(85, '正在生成GeoJSON...');
            
            if (validCount === 0) {
                throw new Error('没有找到有效的坐标数据');
            }
            
            // 创建GeoJSON对象
            const geojson = {
                type: 'FeatureCollection',
                features: features,
                metadata: {
                    source: path.basename(inputPath),
                    totalRows: lines.length - 1,
                    validFeatures: validCount,
                    invalidRows: invalidCount,
                    xColumn: xColumnName,
                    yColumn: yColumnName,
                    createdAt: new Date().toISOString()
                }
            };
            
            this.updateProgress(95, '正在写入文件...');
            
            // 写入文件
            fs.writeFileSync(outputPath, JSON.stringify(geojson, null, 2));
            
            this.updateProgress(100, '转换完成');
            
            this.logger.success(`成功转换 ${validCount} 个点要素`);
            if (invalidCount > 0) {
                this.logger.warning(`跳过 ${invalidCount} 行无效数据`);
            }
            this.logger.info(`输出文件: ${outputPath}`);
            
        } catch (error) {
            throw new Error(`CSV转GeoJSON失败: ${error.message}`);
        }
    }

    /**
     * 预览数据
     */
    async previewData() {
        try {
            const inputPath = this.elements.convertInputFile.value;
            
            this.logger.info('正在预览数据...');
            
            switch (this.currentConvertType) {
                case 'shp2geojson':
                    await this.previewShapefile(inputPath);
                    break;
                case 'geojson2shp':
                    await this.previewGeoJSONFile(inputPath);
                    break;
                case 'csv2geojson':
                    await this.previewCsvData();
                    break;
                default:
                    this.logger.warning('当前转换类型暂不支持预览');
            }
        } catch (error) {
            this.logger.error(`预览失败: ${error.message}`);
        }
    }

    /**
     * 预览Shapefile
     * @param {string} filePath - 文件路径
     */
    async previewShapefile(filePath) {
        try {
            const encoding = this.elements.encodingSelect.value;
            let featureCount = 0;
            let sampleFeature = null;
            
            await shapefile.read(filePath, undefined, {
                encoding: encoding === 'utf8' ? 'utf8' : encoding
            }).then(collection => {
                if (collection && collection.features) {
                    featureCount = collection.features.length;
                    sampleFeature = collection.features[0];
                }
            });
            
            this.logger.info(`文件包含 ${featureCount} 个要素`);
            
            if (sampleFeature) {
                const geometryType = sampleFeature.geometry ? sampleFeature.geometry.type : '未知';
                const propertyCount = sampleFeature.properties ? Object.keys(sampleFeature.properties).length : 0;
                
                this.logger.info(`几何类型: ${geometryType}`);
                this.logger.info(`属性字段数: ${propertyCount}`);
                
                if (sampleFeature.properties && propertyCount > 0) {
                    const propertyNames = Object.keys(sampleFeature.properties).slice(0, 5);
                    this.logger.info(`属性字段: ${propertyNames.join(', ')}${propertyCount > 5 ? '...' : ''}`);
                }
            }
            
        } catch (error) {
            throw new Error(`预览Shapefile失败: ${error.message}`);
        }
    }

    /**
     * 预览GeoJSON文件
     * @param {string} filePath - 文件路径
     */
    async previewGeoJSONFile(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf8');
            const geojson = JSON.parse(content);
            
            if (!geojson) {
                this.logger.error('无法解析GeoJSON文件');
                return;
            }
            
            if (geojson.type === 'FeatureCollection' && Array.isArray(geojson.features)) {
                const features = geojson.features;
                const featureCount = features.length;
                
                this.logger.info(`GeoJSON文件包含 ${featureCount} 个要素`);
                
                if (featureCount > 0) {
                    // 统计几何类型
                    const geometryTypes = {};
                    features.forEach(feature => {
                        if (feature.geometry) {
                            const type = feature.geometry.type;
                            geometryTypes[type] = (geometryTypes[type] || 0) + 1;
                        }
                    });
                    
                    this.logger.info(`几何类型分布: ${Object.entries(geometryTypes).map(([type, count]) => `${type}: ${count}`).join(', ')}`);
                    
                    // 显示属性信息
                    const sampleFeature = features[0];
                    if (sampleFeature.properties) {
                        const propertyNames = Object.keys(sampleFeature.properties);
                        const propertyCount = propertyNames.length;
                        
                        this.logger.info(`属性字段数: ${propertyCount}`);
                        if (propertyCount > 0) {
                            this.logger.info(`属性字段: ${propertyNames.slice(0, 5).join(', ')}${propertyCount > 5 ? '...' : ''}`);
                        }
                    }
                }
            } else if (geojson.type === 'Feature') {
                this.logger.info('GeoJSON文件包含单个要素');
                if (geojson.geometry) {
                    this.logger.info(`几何类型: ${geojson.geometry.type}`);
                }
                if (geojson.properties) {
                    const propertyCount = Object.keys(geojson.properties).length;
                    this.logger.info(`属性字段数: ${propertyCount}`);
                }
            } else {
                this.logger.warning(`不支持的GeoJSON类型: ${geojson.type}`);
            }
            
        } catch (error) {
            throw new Error(`预览GeoJSON文件失败: ${error.message}`);
        }
    }

    /**
     * 输入文件变化处理
     */
    async onInputFileChange() {
        const inputPath = this.elements.convertInputFile.value;
        
        // 如果是CSV转GeoJSON，需要解析CSV文件的列
        if (this.currentConvertType === 'csv2geojson' && inputPath) {
            await this.loadCSVColumns(inputPath);
        }
        
        this.updateButtons();
    }

    /**
     * 加载CSV文件的列信息
     * @param {string} filePath - CSV文件路径
     */
    async loadCSVColumns(filePath) {
        try {
            this.logger.info('正在分析CSV文件结构...');
            
            const encoding = this.elements.encodingSelect.value || 'utf8';
            const content = fs.readFileSync(filePath, encoding);
            const lines = content.split('\n');
            
            if (lines.length === 0) {
                throw new Error('CSV文件为空');
            }
            
            // 解析第一行作为列名
            const firstLine = lines[0].trim();
            const columns = this.parseCSVLine(firstLine);
            
            if (columns.length === 0) {
                throw new Error('无法解析CSV文件的列信息');
            }
            
            // 更新列选择下拉框
            this.updateColumnSelects(columns);
            
            this.logger.info(`发现 ${columns.length} 个列: ${columns.join(', ')}`);
            
        } catch (error) {
            this.logger.error(`分析CSV文件失败: ${error.message}`);
            this.clearColumnSelects();
        }
    }

    /**
     * 解析CSV行
     * @param {string} line - CSV行内容
     * @returns {Array} 列数组
     */
    parseCSVLine(line) {
        const columns = [];
        let current = '';
        let inQuotes = false;
        
        for (let i = 0; i < line.length; i++) {
            const char = line[i];
            
            if (char === '"') {
                inQuotes = !inQuotes;
            } else if (char === ',' && !inQuotes) {
                columns.push(current.trim().replace(/^"|"$/g, ''));
                current = '';
            } else {
                current += char;
            }
        }
        
        // 添加最后一列
        if (current || line.endsWith(',')) {
            columns.push(current.trim().replace(/^"|"$/g, ''));
        }
        
        return columns;
    }

    /**
     * 更新列选择下拉框
     * @param {Array} columns - 列名数组
     */
    updateColumnSelects(columns) {
        const xSelect = this.elements.csvXColumnSelect;
        const ySelect = this.elements.csvYColumnSelect;
        
        if (!xSelect || !ySelect) return;
        
        // 清空现有选项
        xSelect.innerHTML = '<option value="">请选择X坐标列</option>';
        ySelect.innerHTML = '<option value="">请选择Y坐标列</option>';
        
        // 添加列选项
        columns.forEach((column, index) => {
            const xOption = document.createElement('option');
            xOption.value = index;
            xOption.textContent = column;
            xSelect.appendChild(xOption);
            
            const yOption = document.createElement('option');
            yOption.value = index;
            yOption.textContent = column;
            ySelect.appendChild(yOption);
        });
        
        // 启用预览按钮
        if (this.elements.previewCsvBtn) {
            this.elements.previewCsvBtn.disabled = false;
        }
    }

    /**
     * 清空列选择下拉框
     */
    clearColumnSelects() {
        const xSelect = this.elements.csvXColumnSelect;
        const ySelect = this.elements.csvYColumnSelect;
        
        if (xSelect) {
            xSelect.innerHTML = '<option value="">请先选择CSV文件</option>';
        }
        
        if (ySelect) {
            ySelect.innerHTML = '<option value="">请先选择CSV文件</option>';
        }
        
        // 禁用预览按钮
        if (this.elements.previewCsvBtn) {
            this.elements.previewCsvBtn.disabled = true;
        }
    }

    /**
     * 预览CSV数据
     */
    async previewCsvData() {
        try {
            const inputPath = this.elements.convertInputFile.value;
            if (!inputPath) {
                this.logger.error('请先选择CSV文件');
                return;
            }
            
            this.logger.info('正在预览CSV数据...');
            
            const encoding = this.elements.encodingSelect.value || 'utf8';
            const content = fs.readFileSync(inputPath, encoding);
            const lines = content.split('\n').filter(line => line.trim());
            
            if (lines.length === 0) {
                this.logger.error('CSV文件为空');
                return;
            }
            
            const totalRows = lines.length - 1; // 减去标题行
            this.logger.info(`CSV文件包含 ${totalRows} 行数据`);
            
            // 显示前几行数据
            const previewLines = Math.min(5, lines.length);
            this.logger.info('数据预览:');
            
            for (let i = 0; i < previewLines; i++) {
                const columns = this.parseCSVLine(lines[i]);
                const rowType = i === 0 ? '标题行' : `第${i}行`;
                this.logger.info(`${rowType}: ${columns.join(' | ')}`);
            }
            
            if (lines.length > 5) {
                this.logger.info(`... 还有 ${lines.length - 5} 行数据`);
            }
            
        } catch (error) {
            this.logger.error(`预览CSV数据失败: ${error.message}`);
        }
    }

    /**
     * 清除设置
     */
    clearSettings() {
        this.elements.convertInputFile.value = '';
        this.elements.convertOutputFile.value = '';
        this.clearColumnSelects();
        this.updateButtons();
        this.logger.info('已清除文件设置');
    }

    /**
     * 清除文件路径
     */
    clearFiles() {
        this.elements.convertInputFile.value = '';
        this.elements.convertOutputFile.value = '';
        this.clearColumnSelects();
        this.updateButtons();
    }

    /**
     * 更新按钮状态
     */
    updateButtons() {
        const hasInputFile = this.elements.convertInputFile?.value.trim() !== '';
        const hasOutputFile = this.elements.convertOutputFile?.value.trim() !== '';
        
        let canStart = hasInputFile && hasOutputFile && !this.isProcessing;
        
        // 对于CSV转GeoJSON，还需要检查坐标列选择
        if (this.currentConvertType === 'csv2geojson') {
            const hasXColumn = this.elements.csvXColumnSelect?.value !== '';
            const hasYColumn = this.elements.csvYColumnSelect?.value !== '';
            canStart = canStart && hasXColumn && hasYColumn;
        }
        
        if (this.elements.startConvertBtn) {
            this.elements.startConvertBtn.disabled = !canStart;
        }
        
        if (this.elements.previewBtn) {
            this.elements.previewBtn.disabled = !hasInputFile || this.isProcessing;
        }
    }

    /**
     * 显示进度条
     */
    showProgress() {
        if (this.elements.convertProgressSection) {
            this.elements.convertProgressSection.classList.remove('hidden');
        }
    }

    /**
     * 隐藏进度条
     */
    hideProgress() {
        if (this.elements.convertProgressSection) {
            this.elements.convertProgressSection.classList.add('hidden');
        }
    }

    /**
     * 更新进度
     * @param {number} percent - 进度百分比
     * @param {string} text - 进度文本
     */
    updateProgress(percent, text) {
        if (this.elements.convertProgressFill) {
            this.elements.convertProgressFill.style.width = `${percent}%`;
        }
        
        if (this.elements.convertProgressText) {
            this.elements.convertProgressText.textContent = text;
        }
        
        if (this.elements.convertProgressPercent) {
            this.elements.convertProgressPercent.textContent = `${percent}%`;
        }
    }

    /**
     * 取消当前操作
     */
    cancelOperation() {
        if (this.isProcessing) {
            this.isProcessing = false;
            this.updateButtons();
            this.hideProgress();
            this.logger.warning('转换操作已取消');
        }
    }

    /**
     * 获取工具状态
     * @returns {Object} 工具状态
     */
    getToolStatus() {
        return {
            isProcessing: this.isProcessing,
            currentConvertType: this.currentConvertType,
            hasInputFile: this.elements.convertInputFile?.value.trim() !== '',
            hasOutputFile: this.elements.convertOutputFile?.value.trim() !== ''
        };
    }
}

module.exports = DataConvertTool;